package com.lzq.system.service.impl;

import com.lzq.api.code.SystemCode;
import com.lzq.api.commons.SystemUtils;
import com.lzq.system.entity.UserEntity;
import com.lzq.system.info.UserInfo;
import com.lzq.system.repository.UserRepository;
import com.lzq.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    final int ZERO = 0;
    final int MAX_ACCOUNT = 6;
    final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserRepository UserRepository;

    /**
     * 添加用户
     * @param userEntity
     * @return 是否成功
     */
    @Override
    public boolean addUser(UserEntity userEntity){
        UserInfo user = null;

        logger.info("system user service addUser start" + userEntity);
        logger.info("system user service addUser UserRepository save start");
        try {
            user = UserRepository.save(transformed(userEntity));
        } catch (Exception exception) {
            logger.error("system user service addUser fail" + exception);
        }
        //调用userRepository保存用户信息

        logger.info("system user service addUser UserRepository save end");

        if(!SystemUtils.isNull(user) && user.getUid() != ZERO) {
            logger.info("system user service addUser success");
            return true;
        }
        logger.info("system user service addUser fail");
        return false;
    }



    /**
     * 删除用户
     * 修改用户uid
     * @param uid
     * @return 是否成功
     */
    @Override
    public boolean delUser(String uid) {

        //删除一条删除多条的业务逻辑
        String[] ids = uid.split(",");

        if(SystemUtils.isNull(ids) || ids.length == 0) {
            logger.info("system user delUser uid is wrongs");
            return false;
        }

        //删除一条
        if(ids.length == 1) {
            //先查询，后更新
            try {
                logger.info("system user delUser del one user start");
                //把string类型的ids的第一个元素转换成long类型
                Long id = Long.parseLong(ids[0]);
                UserInfo userInfo = UserRepository.findById(id).get();
                userInfo.setUstatus(1);
                UserRepository.save(userInfo);
                logger.info("system user delUser UserRepository success");
                return true;
            } catch (Exception exception) {
                logger.error("system user delUser UserRepository fail");
                return false;
            }
        } else {
          //删除多条
            try {
                logger.info("system user delUser del multiple user start");
                //repository层
                Set<Long> sets = new HashSet<>();
                for(String id : ids) {
                    sets.add(Long.parseLong(id));
                }
                UserRepository.updates(sets);
                logger.info("system user delUser UserRepository success");
                return true;
            } catch (Exception excetion) {
                logger.error("system user delUser UserRepository fail");
                return false;
            }
        }
    }

    /**
     * 更新用户数据
     * @param userEntity
     * @return 是否成功
     */
    @Override
    public boolean updateUser(UserEntity userEntity) {

        //先查询，后更新
        UserInfo userInfo = UserRepository.findById(userEntity.getUid()).get();

        if(!SystemUtils.isNUllOrEmpty(userEntity.getUaccount()) && userEntity.getUaccount().length() < MAX_ACCOUNT) {
            userInfo.setUaccount(userEntity.getUaccount());
            logger.info("system user updateUser Uaccount update");
        }

        if(!SystemUtils.isNUllOrEmpty(userEntity.getUphone())) {
            userInfo.setUphone(userEntity.getUphone());
            logger.info("system user updateUser Uphone update");
        }

        try {
            logger.info("system user updateUser UserRepositoty start");
            UserRepository.save(userInfo);
            logger.info("system user updateUser UserRepositoty success");
            return true;
        } catch (Exception exception) {
            logger.info("system user updateUser UserRepositoty fail");
            return false;
        }

    }




    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<UserEntity> findallUser() {
        List<UserInfo> lists = UserRepository.findAll();

        List<UserEntity> allUser = new ArrayList<>();

        logger.info("system user service intranformed start:" + lists);

        for(UserInfo info : lists) {
            allUser.add(intransformed(info));
        }
        logger.info("system user service intranformed success userEntity:" + allUser);

        return allUser;
    }



    /**
     * 条件查询
     * @param userEntity
     * @return
     */
    @Override
    public List<UserEntity> findAllUserByWhere(UserEntity userEntity) {
        logger.info("system user findAllUserByWhere UserServiceImpl start");
        UserInfo userInfo = transformed(userEntity);
        logger.info("system user findAllUserByWhere UserServiceImpl end transformed:" + userInfo);

        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("uphone",m->m.contains())
                .withIgnorePaths("uid")
                .withIgnorePaths("ustatus");

        //example会把不为空的数据转换成查询条件，例如若uphone不会空，则example就生成为userInfo.getUphone()
        //可以使用List<UserInfo> users = userRepository.findAll(Example.of(userInfo))查询所有
        Example<UserInfo> example = Example.of(userInfo,matcher);
        logger.info("system user findAllUserByWhere UserServiceImpl Example.of:" + example);

        logger.info("system user findAllUserByWhere UserRepository start");
        List<UserInfo> userInfoList = UserRepository.findAll(example);
        logger.info("system user findAllUserByWhere UserRepository end userInfoList:" + userInfoList);
        List<UserEntity> userEntities = new ArrayList<>();

        for(UserInfo info : userInfoList) {
            userEntities.add(intransformed(info));
        }
        logger.info("system user findAllUserByWhere UserServiceImpl intransformed:" + userEntities);

        logger.info("system user findAllUserByWhere UserServiceImpl start");
        return userEntities;
    }


    /**
     * 根据时间查询
     * @param t1
     * @param t2
     * @return
     */
    @Override
    public List<UserEntity> findUserByTime(String t1,String t2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        List<UserInfo> users = null;
        try {
            users = UserRepository.findAllByUtimeBetween(sdf.parse(t1),sdf.parse(t2));
            logger.info("system user findUsersByTime impl  users:" + users);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return intransformedList(users);
    }


    /**
     * 将listuserinfo转换为listuserentity
     * @param userInfos
     * @return
     */
    private List<UserEntity> intransformedList(List<UserInfo> userInfos) {
        List<UserEntity> users = new ArrayList<>();

        for(UserInfo userInfo : userInfos) {
            users.add(intransformed(userInfo));
        }

        return users;
    }

    /**
     * 将UserInfo转换为userEntity
     *
     */
    private UserEntity intransformed(UserInfo userInfo) {


        UserEntity userEntity = new UserEntity();

        userEntity.setUid(userInfo.getUid());
        userEntity.setUname(userInfo.getUname());
        userEntity.setUaccount(userInfo.getUaccount());
        userEntity.setUpass("*******");
        userEntity.setUmail(userInfo.getUmail());
        userEntity.setUphone(userInfo.getUphone());
        userEntity.setT1(userInfo.getT1());
        userEntity.setT2(userInfo.getT2());


        return userEntity;
    }

    /**
     * 将userEntity转换成UserInfo
     * @param userEntity
     * @return UserInfo
     */
    private UserInfo transformed(UserEntity userEntity) {

        logger.info("system user service tranformed start:" + userEntity);

        UserInfo userInfo = new UserInfo();

        userInfo.setUid(userEntity.getUid());
        userInfo.setUname(userEntity.getUname());
        userInfo.setUaccount(userEntity.getUaccount());
        userInfo.setUpass(userEntity.getUpass());
        userInfo.setUmail(userEntity.getUmail());
        userInfo.setUphone(userEntity.getUphone());
        userInfo.setT1(userEntity.getT1());
        userInfo.setT2(userEntity.getT2());

        logger.info("system user service tranformed end userinfo:" + userInfo);

        return userInfo;
    }
}
